package com.glela.sensitiveWords.component;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.glela.cache.redis.RedisKeys;
import com.glela.cache.redis.RedisUtil;
import com.glela.common.util.Config;
import com.glela.sensitiveWords.beans.Node;
import com.glela.sensitiveWords.beans.SensitiveWordsFilterResult;
import com.glela.sensitiveWords.util.HttpDownloadUtils;
import com.glela.sensitiveWords.util.SensitiveWordsFilterUtils;

/**
 * Created by liujie 
 */
@Component
public class SensitiveWordsFilterComponent {
    private static Logger logger = LoggerFactory.getLogger(SensitiveWordsFilterComponent.class);

    @Autowired
    private RedisUtil redisUtil;

    public boolean check(String contents) {
        try {
            Node node = null;
            try {
                node = redisUtil.getEntity(RedisKeys.SENSITIVE_WORDS_NODE, Node.class);
            } catch (Exception e) {
                logger.error("redis获取敏感词数据出错", e);
            }
            if (node == null) {
                node = SensitiveWordsFilterUtils.tree;
            }

            if (node == null || node.getChildren().isEmpty()) {
                node = HttpDownloadUtils.downloadAndParseSensitiveWordsFile();
                redisUtil.set(RedisKeys.SENSITIVE_WORDS_NODE, node);
            }
            SensitiveWordsFilterUtils.tree = node;
            SensitiveWordsFilterResult result = SensitiveWordsFilterUtils.filterText(contents == null ? "" : contents, '*');
            logger.info("敏感词检查， contents={}, result={}", contents, result.toString());
            return StringUtils.isEmpty(result.getBadWords());
        } catch (Exception e) {
            logger.error("敏感词检测接口错误", e);
        }
        return true;
    }

    public Node reloadSensitiveWordsFile() throws Exception {
        Node node  = SensitiveWordsFilterUtils.parseFile(Config.getString("sensitiveWords_file_path"));
        redisUtil.set(RedisKeys.SENSITIVE_WORDS_NODE, node);
        return node;
    }
}
